<template>
  <div class="main">
    <el-card class="search-box">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
        <el-form-item label="模板名称：" prop="storeName">
          <el-input
            v-model="queryParams.templateName"
            placeholder="请输入模板名称"
            clearable
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getList"
            >查询</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 8px">
      <el-button type="primary" style="margin-bottom: 10px" @click="openPop"
        >添加运费模板</el-button
      >
      <el-table
        :data="tableData"
        v-loading="loading"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#000000',
        }"
        style="width: 100%"
      >
        <el-table-column prop="id" label="id"> </el-table-column>
        <el-table-column prop="templateName" label="模板名称">
        </el-table-column>
        <el-table-column prop="type" label="计费方式"> </el-table-column>
        <el-table-column prop="createTime" label="添加时间"> </el-table-column>
        <el-table-column prop="edit" label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleUpdate(scope.row.id)"
            >
              编辑
            </el-button>

            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNumber"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      title="运费模板"
      :visible.sync="dialogVisible"
      width="1200px"
      :before-close="handleClose"
    >
      <el-dialog
        width="800px"
        title="选择区域"
        :visible.sync="innerVisible"
        append-to-body
      >
        <div class="header-top">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            name="regionId"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
        </div>
        <div class="body-box">
          <el-checkbox-group
            v-model="checkModule"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="city in cities"
              :label="city.regionId"
              :value="city.regionName"
              :key="city.regionId"
              @change="getcheckModule(city)"
              >{{ city.regionName }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </el-dialog>
      <el-dialog
        width="800px"
        title="选择区域2"
        :visible.sync="innerVisibleTwo"
        append-to-body
      >
        <div class="header-top">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAllTwo"
            @change="handleCheckAllChangeTwo"
            >全选</el-checkbox
          >
        </div>
        <div class="body-box">
          <el-checkbox-group
            v-model="checkedCitiesTwo"
            @change="handleCheckedCitiesChangeTwo"
          >
            <el-checkbox
              v-for="(city, index) in cities"
              :label="city"
              :key="index"
              >{{ city.regionName }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </el-dialog>

      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="130px"
        class="demo-ruleForm"
      >
        <el-form-item label="活动名称" prop="templateName">
          <el-input v-model="ruleForm.templateName"></el-input>
        </el-form-item>
        <el-form-item label="特殊资源" prop="type">
          <el-radio-group v-model="ruleForm.type">
            <el-radio :label="1">按件数</el-radio>
            <el-radio :label="2">按质量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="通用运费设置：" prop="type">
          <div class="right-box">
            <div class="right-header">
              <p>首件{{ ruleForm.type == 1 ? "" : "重量KG" }}</p>
              <p>运费(元）</p>
              <p>续件{{ ruleForm.type == 1 ? "" : "重量KG" }}</p>
              <p>续费(元）</p>
            </div>
            <div class="right-header right-header-box">
              <p>
                <el-input-number
                  v-model="ruleForm.initQuantity"
                  controls-position="right"
                  :precision="2"
                  :step="0.1"
                ></el-input-number>
              </p>
              <p>
                <el-input-number
                  v-model="ruleForm.initFee"
                  controls-position="right"
                  :precision="2"
                  :step="0.1"
                ></el-input-number>
              </p>
              <p>
                <el-input-number
                  v-model="ruleForm.addQuantity"
                  controls-position="right"
                  :precision="2"
                  :step="0.1"
                ></el-input-number>
              </p>
              <p>
                <el-input-number
                  v-model="ruleForm.addFee"
                  controls-position="right"
                  :precision="2"
                  :step="0.1"
                ></el-input-number>
              </p>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="特殊运费设置：" prop="type">
          <el-button type="primary" @click="innerVisible = true"
            >添加区域</el-button
          >
          <div class="right-box" style="margin-top: 10px">
            <div class="right-header">
              <p>可配送区域</p>
              <p>首件重量(KG）</p>
              <p>运费(元）</p>
              <p>续件重量(KG）</p>
              <p>运费(元）</p>
              <p>操作</p>
            </div>
            <div style="max-height: 222px; overflow: auto">
              <div
                class="right-header right-header-box"
                v-for="(item, index) of ruleForm.accessRegionList"
                :key="index"
              >
                <p>
                  <el-input
                    v-model="item.regionName"
                    :disabled="true"
                    placeholder="请输入内容"
                    >{{ item.id }}</el-input
                  >
                </p>
                <p>
                  <el-input-number
                    v-model="item.initQuantity"
                    controls-position="right"
                    :precision="2"
                    :step="0.1"
                  ></el-input-number>
                </p>
                <p>
                  <el-input-number
                    v-model="item.initFee"
                    controls-position="right"
                    :precision="2"
                    :step="0.1"
                  ></el-input-number>
                </p>
                <p>
                  <el-input-number
                    v-model="item.addQuantity"
                    controls-position="right"
                    :precision="2"
                    :step="0.1"
                  ></el-input-number>
                </p>
                <p>
                  <el-input-number
                    v-model="item.addFee"
                    controls-position="right"
                    :precision="2"
                    :step="0.1"
                  ></el-input-number>
                </p>
                <p>
                  <el-button type="danger" @click="removeRegion(item)"
                    >删除</el-button
                  >
                </p>
              </div>
            </div>
          </div>
        </el-form-item>
        <!-- {{ruleForm.denyRegionList }} -->
        <el-form-item label="指定不送达区域：" prop="type">
          <el-button type="primary" @click="innerVisibleTwo = true"
            >添加区域</el-button
          >

          <div class="right-box" style="margin-top: 10px">
            <div class="right-header">
              <p>不送达区域</p>
              <p>操作</p>
            </div>
            <div style="max-height: 222px; overflow: auto">
              <div
                class="right-header right-header-box"
                v-for="(item, index) of ruleForm.denyRegionList"
                :key="index"
              >
                <p>{{ item.regionName }}</p>

                <p>
                  <el-button type="danger">删除</el-button>
                </p>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisibleClose"
      width="30%"
      :before-close="handleDeleteClose"
    >
      <span>确定进行删除吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleClose = false">取 消</el-button>
        <el-button type="primary" @click="submitDelete()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import {
  queryStoreList,
  addExpressTemplate,
  deleteTemplate,
  queryTemplateDetail,
  updateExpressTemplate,
} from "@/api/order";
import addressList from "@/utils/AddressData";
const addressData = addressList.map((item, index) => {
  return Object.assign(
    {},
    {
      regionId: item.regionId,
      regionName: item.regionName,
    }
  );
});

export default {
  name: "",
  components: { Pagination },
  props: {},
  data() {
    return {
      queryParams: {
        pageNumber: 1,
        pageSize: 10,
        templateName: "",
      },
      loading: true,
      tableData: [],
      total: 0,
      dialogVisible: false,
      innerVisible: false,
      innerVisibleTwo: false,
      ruleForm: {
        templateName: "",
        type: 1,
        initQuantity: 0,
        initFee: 0,
        addQuantity: 0,
        addFee: 0,
        accessRegionList: [],
        denyRegionList: [],
      },
      input: "",
      cities: addressData,
      cityList: [],
      cityListTwo: [],
      rules: {
        templateName: [
          { required: true, message: "请输入模板名称", trigger: "blur" },
        ],
      },
      checkedCities: [],
      checkedCitiesTwo: [],
      checkAll: false,
      checkAllTwo: false,
      isIndeterminate: true,
      dialogVisibleClose: false,
      templateId: null,
      openType: 1,
      checkarr:[],
      checkModule:[]
    };
  },
  watch: {},
  computed: {},
  methods: {
    async getList() {
      const res = await queryStoreList(this.queryParams);
      this.loading = false;
      this.tableData = res.data.list;
      this.total = res.data.total;
    },
    async getQueryExpressTemplateList() {
      this.cityList = this.cities.map((item) => item.id);
    },
    resetQuery() {
      this.queryParams = {
        pageNumber: 1,
        pageSize: 10,
        templateName: "",
      };
    },
    handleClose() {
      this.dialogVisible = false;
      this.restList();
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities : [];
      this.checkModule =  this.checkedCities.map(item=>item.regionId)
      this.isIndeterminate = false;
      this.getAccessRegionList();
    },
    handleCheckAllChangeTwo(val) {
      this.checkedCitiesTwo = val ? this.cities : [];
      this.isIndeterminate = false;
      this.getAccessRegionListTwo();
    },
    handleCheckedCitiesChange(value) {
      console.log(value,'132123')
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
      this.getAccessRegionList();
    },
    handleCheckedCitiesChangeTwo(value) {
      let checkedCount = value.length;
      this.checkAllTwo = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
      this.getAccessRegionListTwo();
    },
    getAccessRegionList() {
      this.ruleForm.accessRegionList = this.checkedCities.map((item, index) => {
        return Object.assign(
          {},
          {
            regionId: item.regionId,
            regionName: item.regionName,
            initQuantity: null,
            initFee: null,
            addQuantity: null,
            addFee: null,
          }
        );
      });
    },
    getAccessRegionListTwo() {
      this.ruleForm.denyRegionList = this.checkedCitiesTwo.map(
        (item, index) => {
          return Object.assign(
            {},
            {
              regionId: item.regionId,
              regionName: item.regionName,
            }
          );
        }
      );
    },
    removeRegion(item) {
      var index = this.ruleForm.accessRegionList.indexOf(item);
      if (index !== -1) {
        this.ruleForm.accessRegionList.splice(index, 1);
        this.checkModule.splice(index, 1);
        this.checkedCities.splice(index, 1);
      }
    },
    openPop() {
      this.dialogVisible = true;
      this.openType = 1;
      this.checkModule = []
      this.restList();
    },
    handleDeleteClose() {
      this.dialogVisibleClose = false;
    },
    handleDelete(id) {
      this.dialogVisibleClose = true;
      this.templateId = id;
    },
    handleUpdate(id) {
      queryTemplateDetail(id).then((res) => {
        if (res.code == 200) {
          this.dialogVisible = true;
          this.ruleForm = res.data;
          this.checkedCities = res.data.accessRegionList.map((item, index) => {
            return Object.assign(
              {},
              {
                regionId: item.regionId,
                regionName: item.regionName,
                // initQuantity: null,
                // initFee: null,
                // addQuantity: null,
                // addFee: null,
              }
            );
          });
          this.checkModule = res.data.accessRegionList.map(item=>item.regionId)
          console.log( this.checkModule,'2132')
          // this.checkedCities = res.data.accessRegionList.map(item=>Number(item.regionId))
          this.openType = 2;
        }
      });
    },
    submitDelete() {
      deleteTemplate(this.templateId).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: res.message,
            type: "success",
          });
          this.getList();
          this.dialogVisibleClose = false;
        }
      });
    },
    restList() {
      this.ruleForm = {
        templateName: "",
        type: 1,
        initQuantity: 0,
        initFee: 0,
        addQuantity: 0,
        addFee: 0,
        accessRegionList: [],
        denyRegionList: [],
      };
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.openType == 1) {
            console.log(this.ruleForm);
            this.ruleForm.denyRegionList = this.ruleForm.denyRegionList.map(
              (item) => item.regionId
            );
            addExpressTemplate(this.ruleForm).then((res) => {
              if (res.code == 200) {
                this.dialogVisible = false;
                this.restList();
                this.getList();
                this.$message({
                  message: res.message,
                  type: "success",
                });
              }
            });
          } else {
            updateExpressTemplate(this.ruleForm).then((res) => {
              if (res.code == 200) {
                this.dialogVisible = false;
                this.restList();
                this.getList();
                this.$message({
                  message: res.message,
                  type: "success",
                });
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getcheckModule(item) {
      console.log(item,'item')
      if (this.checkarr.indexOf(item.regionName) == -1) {
        this.checkarr.push(item.regionName);
      } else {
        this.checkarr.splice(this.checkarr.indexOf(item.regionName), 1);
      }

      this.getArrObj(this.checkModule,this.checkarr)
    },
    getArrObj(item,item2){
      const f1 = (key, arr) => arr.map(item => ({
                [key]: item
      }))
      const getMaxArr = (a, b) => (a.length >= b.length) ? a : b;
      const mergeArr = (oldArr, arr) => oldArr.map((item, index) => ({
        'regionId':item,
          ...arr[index]
      }))

      let list1 = f1('regionId', item)
      let list2 = f1('regionName', item2)
      this.checkedCities = mergeArr(getMaxArr(item,item2), list2)
      console.log(this.checkedCities);
    }
  },
  created() {
    this.getList();
    this.getQueryExpressTemplateList();
  },
  mounted() {},
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  box-sizing: border-box;
  border-bottom: 1px solid #ddd;
}
.right-box {
  width: 100%;
  .right-header {
    display: flex;
    width: 100%;
    line-height: 36px;
    background: #fafafa;
  }
  .right-header-box {
    background: #fff;
    padding: 10px 0;
    border-bottom: 1px solid #ddd;
  }
  p {
    flex: 1;
    margin: 0;
    text-align: center;
  }
  .el-input-number--medium {
    width: 100%;
    max-width: 160px;
  }
}
::v-deep .body-box .el-checkbox {
  width: 20%;
  margin-bottom: 10px;
}
</style>